package com.tang.filter;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * @author Tang
 * @classname AbstractDirectTokenFilter
 * @description [  ]
 * @date 2021/5/1 15:47
 */
public abstract class AbstractDirectTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        System.out.println("自定义过滤器开始执行..." + this.getClass().getName());
        try {
            // 判断有没有认证
            Boolean isAuthenticated = Optional.ofNullable(SecurityContextHolder.getContext())
                    .map(SecurityContext::getAuthentication)
                    .map(Authentication::isAuthenticated)
                    .orElse(false);
            String token = request.getHeader(getHeaderName());
            // 认证过了就直接放行
            if (isAuthenticated || StringUtils.isEmpty(token)) {
                doFilter(request, response, filterChain);
                return;
            }
            System.out.println("AbstractDirectTokenFilter 开始验证....");
            // 获取 Authentication
            Authentication authentication = getAuthentication(token);
            // 设置到上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);
            // 成功回调
            onSuccessfulAuthentication(request, response, authentication);
        } catch (Exception e) {
            System.out.println(String.format("exception:%s", e.getMessage()));
            SecurityContextHolder.clearContext();
            // 失败回调
            onUnSuccessfulAuthentication(request, response);
        }
        filterChain.doFilter(request, response);
    }

    protected abstract void onUnSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response);

    protected abstract void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authentication);

    protected abstract Authentication getAuthentication(String token);

    protected abstract String getHeaderName();

}